/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/8/30
 * Time: 23:22
 */
public class Solution {
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int m = mat.length, n = mat[0].length;
        int[][] sum = new int[m + 1][n + 1];
        //初始化前缀和数组
        for (int i = 1; i < sum.length; i++) {
            for (int j = 1; j < sum[0].length; j++) {
                sum[i][j] = sum[i][j - 1] + sum[i - 1][j] - sum[i - 1][j - 1] + mat[i - 1][j - 1];
            }
        }
        //使用前缀和数组
        int[][] ret = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int x1 = Math.max(0, i - k) + 1,y1 = Math.max(0, j - k) + 1;
                int x2 = Math.min(m - 1, i + k) + 1,y2 = Math.min(n - 1, j + k) + 1;
                ret[i][j] = sum[x2][y2] - sum[x1 - 1][y2] - sum[x2][y1 - 1] + sum[x1 - 1][y1 - 1];
            }
        }
        return ret;
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] ints = solution.matrixBlockSum(new int[][]{{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}, 1);
        for (int[] curList : ints){
            for (int i : curList){
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}